package team.scau.laboratory_repair.service;

import com.querydsl.core.QueryResults;
import com.querydsl.core.types.dsl.EntityPathBase;
import com.querydsl.jpa.impl.JPAQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import team.scau.laboratory_repair.common.page.MyPage;
import team.scau.laboratory_repair.common.base.BaseService;
import team.scau.laboratory_repair.common.utils.ztree.ZTreeNode;
import team.scau.laboratory_repair.modules.po.Area;
import team.scau.laboratory_repair.modules.po.QArea;
import team.scau.laboratory_repair.modules.po.User;
import team.scau.laboratory_repair.modules.repository.AreaRepository;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description:
 * @Author:ZTF
 * @Date:2018/5/23 16:15
 */
@Service
public class AreaService extends BaseService<Area, AreaRepository> {
    @Autowired
    private AreaRepository areaRepository;
    @Autowired
    private UserService userService;
    private QArea qArea = QArea.area;
    @Override
    public AreaRepository getRepository() {
        return areaRepository;
    }

    @Override
    public EntityPathBase<Area> getQBase() {
        return qArea;
    }

    public QueryResults<Area> listOrByExample(Area area, MyPage page) {
        JPAQuery<Area> jpaQuery = queryFactory.select(qArea).from(qArea);
        if (area != null){
            if(StringUtils.isNotBlank(area.getName())) {
                jpaQuery = jpaQuery.where(qArea.name.eq(area.getName()));
            }
            if(area.getManager() != null) {
                jpaQuery = jpaQuery.where(qArea.manager.eq(area.getManager()));
            }
        }
        jpaQuery = jpaQuery.where(qArea.valid.eq(true));
        if (page != null) {
            jpaQuery = jpaQuery.orderBy(page.getSort()).offset(page.getPage()).limit(page.getSize());
        }
        return jpaQuery.fetchResults();

    }


    public List<ZTreeNode> selectStaffTree(Area area) throws Exception {

        List<User> users = userService.listAllStaff();

        List<String> idArray = StringUtils.isBlank(area.getStaffs()) ? new ArrayList<>()
                : Arrays.asList(area.getStaffs().split(","));
        List<ZTreeNode> tree = new ArrayList<>();
        for (User user : users) {
            ZTreeNode treeNode = new ZTreeNode();
            treeNode.setId(user.getId() + "");
            treeNode.setName(user.getUsername());
            if(idArray.contains(user.getId().toString())) {
                treeNode.setChecked(true);
            }
            tree.add(treeNode);
        }
        return tree;
    }
}
